import base64
import sys
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QScrollArea, QFrame, QHBoxLayout, QRadioButton, \
    QPushButton, QLabel, QLineEdit, QGridLayout, QMessageBox
from PyQt5.QtCore import Qt, QObject, pyqtSignal
from chat_user import Chat_User
from View.show_comment import ShopComment
from func import view,thred,imgs
from config import button_config, input_config, frame_config,Text_config
from add_shop import AddShop
from update_shop import UpdateShop
from my_ import My
from datetime import datetime
from information_shops import Information_shops


class OrderUpdateSignal(QObject):
    data_updated = pyqtSignal(dict)

class Menu1(QWidget):
    def __init__(self,parent=None):
        super().__init__()
        self.stop_event=None
        self.parent = parent
        self.client=self.parent.client
        self.user_name=self.parent.user_name
        self.client.add_online(self.user_name)
        self.password=self.parent.password
        self.email=self.parent.email
        self.avatar = self.parent.avatar
        self.is_admin=self.parent.is_admin
        self.user_id = self.parent.user_id
        self.sf=self.parent.sf

        self.order_signal = OrderUpdateSignal()
        self.order_signal.data_updated.connect(self.update_order_display)

        self.setWindowTitle("购物商场")
        self.resize(800, 800)
        self.url='http://127.0.0.1:8000'+'/shop_api'
        self.setStyleSheet("background-color: rgb(255, 255, 255);")
        mainLayout = QVBoxLayout(self)
        mainLayout.setContentsMargins(0,0,0,0)
        self.initUI(mainLayout)
    def initUI(self,mainLayout):
        #界面导航栏
        layout=QHBoxLayout()
        mainLayout.addLayout(layout)
        self.create_navi_search(layout)
        layout1=QHBoxLayout()
        mainLayout.addLayout(layout1)
        self.create_navi_btn(layout1)


        #功能区容器
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        mainLayout.addWidget(scroll)
        self.main_frame=QFrame()
        scroll.setWidget(self.main_frame)
        main_layout = QVBoxLayout(self.main_frame)
        self.shop_manage(main_layout)
    def create_navi_search(self,layout):
        logo = QLabel()
        img=QPixmap('../static/img/logo.png')
        img = img.scaled(100, 100, Qt.KeepAspectRatio)
        logo.setPixmap(img)
        layout.addWidget(logo)
        self.search_input=QLineEdit()
        self.search_input.setStyleSheet(input_config.input_style5)
        self.search_input.setPlaceholderText("请输入您要搜索的商品名或品牌")
        layout.addWidget(self.search_input)
        search_btn=QPushButton('🔍')
        search_btn.setStyleSheet(button_config.button_style6)
        search_btn.setFixedSize(60,60)
        layout.addWidget(search_btn)



        self.my_btn=QPushButton('🙂')
        self.my_btn.setStyleSheet(button_config.button_style6)
        self.my_btn.setFixedSize(60,60)
        layout.addWidget(self.my_btn)



        self.my_btn.clicked.connect(self.my_btn_clicked)


    def create_navi_btn(self,layout):
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        text_list = ['我的店铺🪙', '我的订单💵']
        for text in text_list:
            button = QPushButton(text)
            button.setStyleSheet(button_config.button_style5)
            button.setFixedHeight(30)
            layout.addWidget(button)

            button.clicked.connect(self.btn_clicked)
    def my_btn_clicked(self):
        my = My(self)
        my.exec_()
        text=f'当前账户{self.user_name}'
        self.my_btn.setToolTip(text)
        if self.sf == 'client':
            self.parent.sf='client'
            self.parent.show()
            self.close()
    #处理导航栏功能
    def btn_clicked(self):
        sender=self.sender()
        text=sender.text()
        if self.stop_event is not None:
            self.stop_event.set()
            self.stop_event = None
        view.clear_layout(self.main_frame.layout())
        main_layout = self.main_frame.layout()
        if main_layout is None:  # 如果没有布局则新建
            main_layout = QVBoxLayout(self.main_frame)
        if text == '我的店铺🪙':
            self.shop_manage(main_layout)
        if text=='我的订单💵':
            self.my_orders(main_layout)
#商品管理
    def shop_manage(self,main_layout):
        parser={
            'mode' :2,
            'seller_name' : self.user_name
        }
        shops=self.client.get_shops(parser).get('data')
        layout = QGridLayout()
        main_layout.addLayout(layout)
        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 1)
        self.insert_shop(layout,shops)
        frame = QFrame()
        layout.addWidget(frame)
        frame.setStyleSheet(frame_config.frame_style4)
        frame.setFixedHeight(250)
        layout1 = QVBoxLayout(frame)
        btn1 = QPushButton('➕添加商品')
        btn1.setStyleSheet(button_config.button_style1)
        btn1.setFixedSize(160, 160)
        layout1.addWidget(btn1, alignment=Qt.AlignCenter)
        btn1.clicked.connect(self.add_shop)

    def insert_shop(self,layout,shops):
        for shop in shops:
            shop_name=shop.get('shop_name')
            price=shop.get('price')
            brand=shop.get('brand')
            category=shop.get('category')
            description=shop.get('description')
            avatar=base64.b64decode(shop.get('avatar'))
            num=shop.get('num')
            frame=QFrame()
            layout.addWidget(frame)
            layout1=QVBoxLayout(frame)

            text=f'商品名：{shop_name}'
            label=QLabel(text)
            layout1.addWidget(label)

            text=f'价格：{str(price)}'
            label=QLabel(text)
            layout1.addWidget(label)

            text=f'品牌：{brand}'
            label=QLabel(text)
            layout1.addWidget(label)

            text=f'库存：{num}'
            label=QLabel(text)
            layout1.addWidget(label)

            img_label=QLabel()
            img = QPixmap()
            img.loadFromData(avatar)
            img = img.scaled(120, 120, Qt.KeepAspectRatio)
            img_label.setPixmap(img)
            layout1.addWidget(img_label)
            frame.setFixedHeight(290)
            frame.setStyleSheet(frame_config.frame_style4)

            layout3 = QHBoxLayout()
            layout1.addLayout(layout3)

            btn=QPushButton('修改信息')
            #将给按钮对应商品的信息存储
            btn.setProperty("shop_name", shop_name)
            btn.setProperty("price", price)
            btn.setProperty("brand", brand)
            btn.setProperty("category", category)
            btn.setProperty("description", description)
            btn.setProperty("num", num)
            btn.setProperty("avatar", avatar)
            btn.setStyleSheet(button_config.button_style2)
            layout3.addWidget(btn)
            btn.clicked.connect(self.update_shop_btn_clicked)
            btn=QPushButton('详细信息')
            #将给按钮对应商品的信息存储
            btn.setProperty("shop_name", shop_name)
            btn.setProperty("shop_id", shop.get('ID'))
            btn.setStyleSheet(button_config.button_style1)
            layout3.addWidget(btn)
            btn.clicked.connect(self.information)

            layout3 = QHBoxLayout()
            layout1.addLayout(layout3)

            btn_comment=QPushButton('查看评价')
            btn_comment.setStyleSheet(button_config.button_style3)
            btn_comment.setProperty("shop_name", shop_name)
            btn_comment.setProperty("shop_id", shop.get('ID'))
            layout3.addWidget(btn_comment)
            btn_comment.clicked.connect(self.get_comment)

            btn_delete=QPushButton('下架该商品')
            btn_delete.setStyleSheet(button_config.button_style4)
            btn_delete.setProperty("shop_name", shop_name)
            layout3.addWidget(btn_delete)

            btn_delete.clicked.connect(self.delete_shop_btn_clicked)

    def my_orders(self,main_layout):
        parser={
            'seller_id' : self.user_id
        }
        tem=self.client.get_orders(parser)
        self.show_orders(main_layout,tem)
        if self.stop_event is None:
            self.stop_event=thred.star_thread(thred.seller_request_client,self.client,parser,tem,self.order_signal)
    def show_orders(self,main_layout,data):
        no_finish_order=data.get('no_finish_order')
        finish_order=data.get('finish_order')
        frame=QFrame()
        main_layout.addWidget(frame)
        frame.setStyleSheet(frame_config.frame_style4)
        layout1=QVBoxLayout(frame)
        label=QLabel()
        label.setText('未处理的订单')
        label.setStyleSheet(Text_config.text_style2)
        layout1.addWidget(label)
        for i in range(len(no_finish_order)):
            frame1=QFrame()
            frame1.setStyleSheet(frame_config.frame_style1)
            layout1.addWidget(frame1)
            layout2 = QVBoxLayout(frame1)
            text=f'日期：{no_finish_order[i][0]},商品名：{no_finish_order[i][1]},数量：{no_finish_order[i][2]},用户名{no_finish_order[i][4]}'

            label=QLabel()
            label.setText(text)
            label.setStyleSheet(Text_config.text_style3)
            layout2.addWidget(label)
            frame2=QFrame()
            layout2.addWidget(frame2)
            layout3 = QHBoxLayout(frame2)
            btn_chat=QPushButton()
            btn_chat.setText('私信')
            btn_chat.setProperty('client_name',no_finish_order[i][4])
            layout3.addWidget(btn_chat)
            btn_delete=QPushButton()
            btn_delete.setText('删除')
            btn_delete.setProperty("orders_id", no_finish_order[i][3])
            layout3.addWidget(btn_delete)
            btn_push=QPushButton()
            btn_push.setText('发货')
            btn_push.setProperty("quantity", no_finish_order[i][2])
            btn_push.setProperty("orders_id", no_finish_order[i][3])
            btn_push.setProperty("shop_name", no_finish_order[i][1])
            btn_push.setProperty("user_name", no_finish_order[i][4])

            layout3.addWidget(btn_push)
            btn_chat.clicked.connect(self.chat_user)
            btn_push.clicked.connect(self.push_shop_btn_clicked)
            btn_delete.clicked.connect(self.click_delete_btn)

        label = QLabel()
        label.setText('以处理的订单')
        label.setStyleSheet(Text_config.text_style2)
        layout1.addWidget(label)
        for i in range(len(finish_order)-1,-1,-1):
            frame1 = QFrame()
            frame1.setStyleSheet(frame_config.frame_style1)
            layout1.addWidget(frame1)
            layout2 = QHBoxLayout(frame1)
            text = f'日期：{finish_order[i][0]},商品名：{finish_order[i][1]},数量：{finish_order[i][2]},买家{finish_order[i][3]}'
            label = QLabel()
            label.setText(text)
            label.setStyleSheet(Text_config.text_style3)
            layout2.addWidget(label)
            btn_chat = QPushButton()
            btn_chat.setText('私信')
            btn_chat.setProperty('client_name', finish_order[i][3])
            btn_chat.setFixedWidth(130)
            layout2.addWidget(btn_chat)
            btn_chat.clicked.connect(self.chat_user)
    #检测订单信息发生变化
    def update_order_display(self,data):
        print('数据发送改变')
        view.clear_layout(self.main_frame.layout())
        main_layout = self.main_frame.layout()
        if main_layout is None:  # 如果没有布局则新建
            main_layout = QVBoxLayout(self.main_frame)
        self.show_orders(main_layout,data)
    #查看评论
    def get_comment(self):
        sender = self.sender()
        self.shop_id=sender.property('shop_id')
        self.shop_name=sender.property('shop_name')
        com = ShopComment(self)
        com.exec_()
    #添加商品
    def add_shop(self):
        add_shop=AddShop(self)
        res =add_shop.exec_()
    #修改商品信息
    def update_shop_btn_clicked(self):
        sender=self.sender()
        dic={
            'shop_name':sender.property('shop_name'),
            'price':str(sender.property('price')),
            'brand':sender.property('brand'),
            'category':sender.property('category'),
            'description':sender.property('description'),
            'num':str(sender.property('num')),
            'avatar':sender.property('avatar'),
        }
        update_shop = UpdateShop(self,dic)
        res = update_shop.exec_()
    #查看商品详细信息
    def information(self):
        sender=self.sender()
        self.shop_name=sender.property('shop_name')
        self.shop_id=sender.property('shop_id')
        information=Information_shops(self)
        res =information.exec_()
    #下架商品
    def delete_shop_btn_clicked(self):
        ret = QMessageBox.question(None, "提问", "确定要删除吗", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if ret == QMessageBox.Yes:
            sender = self.sender()
            seller_name = self.user_name
            shop_name = sender.property('shop_name')
            parser = {
                'shop_name': shop_name,
                'seller_name': seller_name,
            }
            dic = self.client.delete_shop(parser)
        else:
            return
    #发货
    def push_shop_btn_clicked(self):
        sender=self.sender()
        quantity=sender.property('quantity')
        orders_id=sender.property('orders_id')
        shop_name=sender.property('shop_name')
        user_name=sender.property('user_name')
        parser1 = {
            'orders_id': orders_id,
        }
        parser2={
            'seller_name':self.user_name,
            'shop_name':shop_name,
            'quantity' : quantity,
        }
        parser3={
            'seller_name': self.user_name,
            'shop_name': shop_name,
            'user_name':user_name,
            'quantity':quantity,
            'data': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        statu=self.client.push_orders(parser1,parser2,parser3)
        if statu:
            QMessageBox.information(None,'提示','成功发货')
            # self.btn_clicked('我的订单💵')
        else:
            QMessageBox.critical(None,'错误','库存不足')
    #点击删除订单按钮
    def click_delete_btn(self):
        sender=self.sender()
        orders_id=sender.property('orders_id')
        parser = {
            'orders_id': orders_id,
        }
        msg=self.client.delete_orders(parser)
        QMessageBox.information(None,'提示',msg)
        # self.btn_clicked('我的订单💵')
    def chat_user(self):
        sender=self.sender()
        self.recv_name=sender.property('client_name')
        print(self.recv_name)
        parser={
            'user_name': self.recv_name,
        }
        self.recv_id = self.client.get_user(parser).get('data').get('user_id')
        my = Chat_User(self)
        my.exec_()
    def imgs_analysis(self,layout2,url,parser,w=None,h=None,mode=None):
        data=self.client.get_view(url,parser)
        if not data.get('img'):
            label=QLabel()
            text=data.get('msg')
            label.setText(text)
            label.setStyleSheet(Text_config.text_style3)
            layout2.addWidget(label)
            return
        if mode==1:
            l=QLabel()
            text=f"用户总销售额：{data.get('seller_sum')}"
            l.setText(text)
            l.setStyleSheet(Text_config.text_style3)
            layout2.addWidget(l)

            l=QLabel()
            text=f"用户总购买额：{data.get('buy_sum')}"
            l.setText(text)
            l.setStyleSheet(Text_config.text_style3)
            layout2.addWidget(l)
        img_label = QLabel()
        img_label.setAlignment(Qt.AlignCenter)
        layout2.addWidget(img_label)
        avatar = base64.b64decode(data.get('img'))
        if w and h:
            avatar=imgs.resize_(avatar,w,h)
        img = QPixmap()
        if img.loadFromData(avatar):
            img_label.setPixmap(img)
        else:
            print("图片加载失败：无效的图片数据")
    #展示用户详细信息
    def closeEvent(self,event):
        if self.stop_event is not None:
            self.stop_event.set()
            self.stop_event = None
        self.client.logout(self.user_name)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window=Menu1()
    window.show()
    sys.exit(app.exec_())
